<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Lib\Util\JWT;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $check_login = true;

    protected $request;

    protected $user_id;

    public function __construct(Request $request)
    {
        $this->request = $request;

        $client_token = $request->header('X-Token') ?? '';
        $payload = JWT::verifyToken($client_token);
        if ($this->check_login && $payload=== false) {
            $this->fail(CODE_ERR_AUTH, '未登陆，请先登录！');
            exit;
        }

        $this->user_id = $payload['user_info']['id'];
    }

    /**
     * 返回成功的请求
     * @param array $data
     * @param string $message
     * @return bool
     */
    public function success(array $data = [], $message = '操作成功')
    {
        $response = [
            'code' => CODE_SUCCESS,
            'message' => $message,
            'payload' => $data ?: (object)[],
        ];

        Log::info(json_encode([
            'response' => $response,
            'request' => Request()->all(),
            'route' => Request()->route()
        ], JSON_UNESCAPED_UNICODE));

        echo json_encode($response, JSON_UNESCAPED_UNICODE);

        return false;
    }

    /**
     * @param int $code
     * @param string|null $message
     * @return bool
     */
    public function fail(int $code = -1, ?string $message = '')
    {
        $response = [
            'code' => $code,
            'message' => $message ?: $GLOBALS['CODE_MESSAGES'][$code] ?? '操作失败',
            'payload' => (object)[],
        ];

        Log::error(json_encode([
            'response' => $response,
            'request' => Request()->all(),
            'route' => Request()->route()
        ], JSON_UNESCAPED_UNICODE));

        echo json_encode($response, JSON_UNESCAPED_UNICODE);

        return false;
    }
}
